package syncdemo;

//儿子接口类
class Son implements Runnable {

    private IceBoxDemo iceBox; //冰箱对象
    private int bigSonNum = 0; //大儿子吃的数量
    private int smallSonNum = 0; //小儿子吃的数量

    public Son(IceBoxDemo iceBox) {
        this.iceBox = iceBox;
    }

    @Override
    public void run() {
        //不停的吃冰棍
        while (true) {
            //谁有iceBox这个对象的锁，谁就有资格进入同步代码块，执行里面的代码。同步代码块执行完后，也会主动交还对象的锁。
            synchronized (iceBox) {

                if (IceBoxDemo.iceScreamNumber <= 0) { //冰棍吃完了。。。。
                    break; //退出循环，也就意味着线程结束...
                }

                IceBoxDemo.iceScreamNumber--;
                if ("大林".equals(Thread.currentThread().getName())) {
                    System.out.println("大林吃了一根冰棍，还剩：" + IceBoxDemo.iceScreamNumber + "根冰棍。");
                    bigSonNum++;
                } else {
                    System.out.println("小林吃了一根冰棍，还剩：" + IceBoxDemo.iceScreamNumber + "根冰棍。");
                    smallSonNum++;
                }

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public void showResult() {
        System.out.println("大林吃了：" + bigSonNum + "根。");
        System.out.println("小林吃了：" + smallSonNum + "根。");
    }
}

public class IceBoxDemo {
    public static int iceScreamNumber = 50; //冰箱里面的50根冰棍

    public static void main(String[] args) {

        IceBoxDemo iceBox = new IceBoxDemo(); //冰箱对象。

        Son son = new Son(iceBox); //Runnable对象

        Thread bigTh = new Thread(son, "大林"); //大儿子线程对象
        Thread smallTh = new Thread(son, "小林"); //小儿子线程对象。

        bigTh.start();  //启动大儿子线程
        smallTh.start();//启动小儿子线程

        try {

            bigTh.join(); //等待两个线程结束
            smallTh.join();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        son.showResult(); // 显示结果
    }
}
